﻿

var queryWeekRuleUrl = ArrangeUrl + "/scheduling/getSchedulingList";
var deleteWeekRuleUrl = ArrangeUrl + "/scheduling/deleteScheduling";
var queryOneRuleInfoUrl = ArrangeUrl + "/DoctorScheduling/getScheduling";
var exportBzPbRuleUrl = ArrangeUrl + "/scheduling/outExcel";

var now = new Date(); //当前日期
var nowYear = now.getYear(); //当前年
var nowDay = now.getDate(); //当前日
var nowMonth = now.getMonth(); //当前月
var nowDayOfWeek = now.getDay(); //今天本周的第几天
var currentFirstDate;

var _mBeginDate = "";
var _mEndDate = "";

$(function () {

    queryBzpb();
    //$("#table_bzpb td > select").on("change", function () {
    //    $(this).css({ "background-color": GetSchedulStatusCss($(this).val()) });
    //});
    setDate(new Date());

    _mBeginDate = getWeekStartDate();
    _mEndDate = getWeekEndDate();

    //上一周
    $("#but_lastweek").click(function () {
        var datestr = setDate(addDate(currentFirstDate, -7));
        var _beginDate = datestr.split("\2")[0];
        var _endDate = datestr.split("\2")[1];

        _mBeginDate = _beginDate;
        _mEndDate = _endDate;

        queryBzpb(_beginDate, _endDate);
    });

    //本周
    $("#but_thisweek").click(function () {
        //setDate(new Date());
        currentFirstDate = new Date();

        _mBeginDate = getWeekStartDate();
        _mEndDate = getWeekEndDate();

        queryBzpb(getWeekStartDate(), getWeekEndDate());
        console.log(getWeekStartDate() + "__" + getWeekEndDate());
    });

    //下一周
    $("#but_nextweek").click(function () {
        var datestr = setDate(addDate(currentFirstDate, 7));
        var _beginDate = datestr.split("\2")[0];
        var _endDate = datestr.split("\2")[1];

        _mBeginDate = _beginDate;
        _mEndDate = _endDate;

        queryBzpb(_beginDate, _endDate);
    });
});


//查询本周排班
function queryBzpb(_beginDate, _endData) {

    if (_beginDate == undefined || _beginDate == "") {
        _beginDate = getWeekStartDate();
    }
    if (_endData == undefined || _endData == "") {
        _endData = getWeekEndDate();
    }
    $("#t_table_bzpb_content").empty();
    var _index = null;
    $.ajax({
        url: queryWeekRuleUrl,
        type: 'get',
        data: {
            deptId: $("#dept_infolist").val(),
            beginDate: _beginDate,
            endDate: _endData
        },
        beforeSend: function () {
            _index = layer.msg("正在加载数据", { icon: 16 });
        },
        success: function (d) {
            layer.close(_index);
            var datatype = "";
            // var d = weekData;
            if (typeof d == "string") {
                datatype = JSON.parse(d);
            } else if (typeof d == "object") {
                datatype = d;
            }
            if (datatype.status == "0") {
                _json_d = datatype;
                /**
                 * 获取排版字典
                 */
                schedulingDictionary();
                if (_json_d.data != null) {
                    var _tableHeadHtm = "<tr>" +
                        "<th style='line-height:35px;'>工号</th>" +
                        "<th style='line-height:35px;'>医生</th>" +
                        "<th style='line-height:35px;'>特聘</th>" +
                        "<th style='line-height:35px;'>职称</th>";
                    for (var i = 0; i < _json_d.data[0].length; i++) {
                        var _datestr = _json_d.data[0][i].schedulingDate;
                        var _weekstr = _json_d.data[0][i].week;
                        var _dateinfoHtml = _datestr + "<p>星期" + ConvertWeek(_weekstr);
                        _tableHeadHtm += "<th>" + _dateinfoHtml + "</th>";
                    }
                    _tableHeadHtm += "<th style='line-height:35px;'></th>";
                    _tableHeadHtm += "</tr>";
                    $("#th_bzpb_head").html(_tableHeadHtm);
                    $("#t_table_bzpb_content").html("");

                    //遍历所有医生
                    var weekHtml = "";
                    for (var j = 0; j < _json_d.data.length; j++) {
                        var _doctorId = _json_d.data[j][0].doctorId;
                        var _doctorName = _json_d.data[j][0].doctorName;
                        var _doctorKey = _json_d.data[j][0].doctorKey;
                        var _doctorTitle = _json_d.data[j][0].doctorTitle;
                        var _schedulingId = _json_d.data[j][0].schedulingId;
                        var _isSpeciallyInvite = _json_d.data[j][0].isSpeciallyInvite;
                        var _isSpeciallyInviteDesc = _isSpeciallyInvite == "1" ? "特聘" : "非特聘";
                        // var _titledesc = _doctorTitle == "1" ? "主治医生" : _doctorTitle == "2" ? "普通医生" : _doctorTitle;
                        // var _titledesc = _doctorTitle == "1" ? "住院医师" : _doctorTitle == "2" ? "主治医师"
                        //     : _doctorTitle == "3" ? "副主任医师" : _doctorTitle == "4" ? "主任医师" : "未设置";
                        var _titledesc =  _json_d.data[j][0].doctorTitleName || ''
                        //是否特聘 0-非特聘 1 特聘；
                        var isSpeciallyInviteHtml = "";
                        if (_isSpeciallyInvite == "0") {
                            isSpeciallyInviteHtml += "<input type='button' class='but_disabled' disabled='disabled' value='删除' onclick='deleteRule(\"" + _doctorId + "\");'/>";
                        } else {
                            isSpeciallyInviteHtml += "<input type='button' class='but_delete' value='删除' onclick='deleteRule(\"" + _doctorId + "\");'/>";
                        }
                        weekHtml += "<tr id='"+ JSON.stringify(_json_d.data[j]) +"'>" +
                            "<td><span>" + _doctorKey + "</span></td>" + //工号
                            "<td id='"+ _doctorId +"'><span>" + _doctorName + "</span></td>" + //医生
                            "<td><span>" + _isSpeciallyInviteDesc + "</span></td>" + //特聘
                            "<td><span>" + _titledesc + "</span></td>" + //职称
                            getWeekScheduleHtml(_json_d.data[j]) +
                            "<td>"+ isSpeciallyInviteHtml +"</td>" +
                            "</tr>";
                    }
                    $("#t_table_bzpb_content").html(weekHtml);
                    $('.multipleSelected1').multiselect({
                        nonSelectedText: '休息',
                        buttonWidth: 107,
                        numberDisplayed:'100',//显示个数设置为最大
                        allSelectedText:'' //全选text设置为空，就可以超过四个也显示了
                    });
                    $('.multipleSelected1').multiselect('refresh');
                }
                else {
                    $("#th_bzpb_head").html("");
                    $("#t_table_bzpb_content").html("");
                }
            } else {
                $("#th_bzpb_head").html("");
                $("#t_table_bzpb_content").html("");
            }
        }
    });

}

/**
 * 获取本周排班select下拉框-共用
 * @param weekSchedulingData
 */
function getWeekScheduleHtml(weekSchedulingData) {
    weekSchedulingData = weekSchedulingData || [];

    var scheduHtml = '';
    for (var k = 0; k < weekSchedulingData.length; k++) {

        var _schedulingType = weekSchedulingData[k].schedulingType;
        var _schedulingDate = weekSchedulingData[k].schedulingDate;

        scheduHtml += '<td>';
        var _select_ava = "";
        if (CompareDate(showToDay(), _schedulingDate)) {
            _select_ava = '<select id="multiple-selected_'+ k +'" multiple="multiple" class="multipleSelected1" disabled="disabled">';
        } else {
            _select_ava = '<select id="multiple-selected_'+ k +'" multiple="multiple" class="multipleSelected1">';
        }
        scheduHtml += _select_ava;
        scheduHtml += (function (index) {
            return initWeekSelectOption(schedulingdicList,weekSchedulingData[k]);
        })(k);
        scheduHtml += '</select>';
        scheduHtml += '</td>';
    }
    return scheduHtml;
}


/***
 *  根据返回值比较勾选与否
 * */
function initWeekSelectOption(dataList,scheduArr) {
    scheduArr = scheduArr || [];
    var _schedulingKey,_schedulingName,frag='';
    for(var i = 0; i < dataList.length; i++){
        _schedulingKey = dataList[i].dicKey;
        _schedulingName = dataList[i].dicName;
        if(isHasWeek(scheduArr,_schedulingKey)){
            frag += "<option selected value='"+ _schedulingKey +"'>"+ _schedulingName +"</option>";
        }else {
            frag += "<option value='"+ _schedulingKey +"'>"+ _schedulingName +"</option>";
        }
    }
    return frag;
}


/**
 * scheduArr数组中的值和dicKey比较，==及选中勾选
 * @param scheduArr：通过排班字典data数据获取
 * @param key：通过排班规则列表接口获取schedulingKey
 * @returns {boolean}
 */
function isHasWeek(scheduArr,key) {
    var bool = false;
    // var _schedulingType = scheduArr.schedulingType;
    var _scheduling = scheduArr.schedulingType;
    var _schedulingType = "";
    if(typeof _scheduling == "string"){
        _schedulingType = JSON.parse(_scheduling);
    }else if(typeof _scheduling == "object"){
        _schedulingType = _scheduling;
    }

    for(var i = 0; i < _schedulingType.length; i++){
        if(_schedulingType[i] == key){
            bool = true;
            break;
        }
    }
    return bool;
}


//删除本周排班
function deleteRule(d) {

    layer.confirm('确定要删除该医生的本周排班吗？', {
        btn: ['取消', '确定'],
        icon: 7,
    }, function () {
        layer.closeAll();
    }, function () {

        $.ajax({
            url: deleteWeekRuleUrl,
            type: 'post',
            data: {
                doctorId: d,
                beginDate: _mBeginDate,
                endDate: _mEndDate
            },
            success: function (d) {
                if (JSON.parse(d).status == "0") {
                    queryBzpb(_mBeginDate, _mEndDate);
                } else {
                    layer.alert("删除失败:" + JSON.parse(d).desc, { icon: 2 })
                }
            }
        });
    });
}


//导出本周排班
function exportWeekArrangeRule() {
    window.open(exportBzPbRuleUrl);
}

function delete_chk(_t) {

    var _ischeked = $(_t).prop("checked");
    console.log(_ischeked + "__");

    //清除选中样式
    $("#t_table_bzpb_content").find("input").each(function () {
        $(this).parent().parent().css({
            "border-top": "",
            "border-bottom": "",
            "border-left": "",
        });

        $(this).parent().parent().nextAll().each(function () {
            $(this).css({
                "border-top": "",
                "border-bottom": "",
            });
        });
        $(this).parent().parent().nextAll().last().css({
            "border-right": "",
        });
    });

    $(_t).parent().parent().css({
        "border-top": "1px solid #3598db",
        "border-bottom": "1px solid #3598db",
        "border-left": "1px solid #3598db",
    });


    $(_t).parent().parent().nextAll().each(function () {
        $(this).css({
            "border-top": "1px solid #3598db",
            "border-bottom": "1px solid #3598db",
        });
    });

    $(_t).parent().parent().nextAll().last().css({
        "border-right": "1px solid #3598db",
    });

}

function addDate(date, n) {
    date.setDate(date.getDate() + n);
    return date;
}

function setDate(date) {

    var week = date.getDay() - 1;
    date = addDate(date, week * -1);
    currentFirstDate = new Date(date);
    var weekArray = new Array();
    for (var i = 0; i < 7; i++) {
        weekArray.push(formatDate(i == 0 ? date : addDate(date, 1)));
    }
    return weekArray[0] + "\2" + weekArray[weekArray.length - 1]
}
